<template>
  <div class="container">
    <div>
      <a-row>
        <a-col :span="8">
          <p>正常人数: {{normal}}人</p>
        </a-col>
        <a-col :span="8">
          <p>预警人数: {{alert}}人</p>
        </a-col>
        <a-col :span="8">
          <p>高危人数: {{danger}}人</p>
        </a-col>
      </a-row>
    </div>
    <h1 style="font-size: 22px">用户健康管理</h1>
    <a-row>
      <a-col :span="20">
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="tableToExcel" style="margin-bottom: 15px; font-size: 18px">
          导出excel表
        </a-button>
      </a-col>
    </a-row>
    <a-table :data-source="data" :columns="columns" :rowKey="record => record.openid"
             @change="onChange">
      <div
        slot="filterDropdown"
        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        style="padding: 8px"
      >
        <a-input
          v-ant-ref="c => (searchInput = c)"
          :placeholder="`Search ${column.dataIndex}`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block;"
          @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        />
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          Search
        </a-button>
        <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
          Reset
        </a-button>
      </div>
      <a-icon
        slot="filterIcon"
        slot-scope="filtered"
        type="search"
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />

      <template slot="customRender" slot-scope="text, record, index, column">
        <span v-if="searchText && searchedColumn === column.dataIndex">
          <template
            v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <mark
              v-if="fragment.toLowerCase() === searchText.toLowerCase()"
              :key="i"
              class="highlight"
            >{{ fragment }}</mark
            >
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
        <template v-else>
          {{ text }}
        </template>
      </template>

      <template slot="operation" slot-scope="text, record">
        <div style="display: inline">
          <a-popconfirm v-if="data.length" title="确定状态设为健康?" @confirm="() => statusChange(record.openid, 0)">
            <a-icon type="safety" style="font-size: 20px"/>
          </a-popconfirm>
          <a-popconfirm v-if="data.length" title="确定状态设为预警?" @confirm="() => statusChange(record.openid, 1)">
            <a-icon type="warning" style="font-size: 20px"/>
          </a-popconfirm>
          <a-popconfirm v-if="data.length" title="确定状态设为危险?" @confirm="() => statusChange(record.openid, 2)">
            <a-icon type="stop" style="font-size: 20px"/>
          </a-popconfirm>
        </div>

      </template>

    </a-table>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        data: [],
        searchText: '',
        searchInput: null,
        searchedColumn: '',
        columns: [
          {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'customRender'
            },
            onFilter: (value, record) =>
              record.name
                .toString()
                .includes(value),
            // 自动添加输入焦点
            onFilterDropdownVisibleChange: visible => {
              if (visible) {
                setTimeout(() => {
                  this.searchInput.focus()
                })
              }
            }
          },
          {
            title: '地址',
            dataIndex: 'address',
            key: 'address',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'customRender'
            },
            onFilter: (value, record) =>
              record.address
                .toString()
                .includes(value),
            // 自动添加输入焦点
            onFilterDropdownVisibleChange: visible => {
              if (visible) {
                setTimeout(() => {
                  this.searchInput.focus()
                })
              }
            }
          },
          {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone'
          },
          {
            title: '是否小区住户',
            dataIndex: 'isResident',
            key: 'isResident',
            customRender: function (text) {
              if (text === 0) {
                return '否'
              } else if (text === 1) {
                return '是'
              } else {
                return text
              }
            },
            filters: [
              {
                text: '否',
                value: 0
              },
              {
                text: '是',
                value: 1
              }
            ],
            onFilter: (value, record) => record.isResident === value
          },
          {
            title: '目前健康状态',
            dataIndex: 'status',
            key: 'status',
            customRender: function (text) {
              if (text === 0) {
                return '健康'
              } else if (text === 1) {
                return '预警'
              } else {
                return '高危'
              }
            },
            filters: [
              {
                text: '健康',
                value: 0
              },
              {
                text: '预警',
                value: 1
              },
              {
                text: '高危',
                value: 2
              }
            ],
            onFilter: (value, record) => record.status === value
          },
          {
            title: '操作',
            dataIndex: 'operation',
            scopedSlots: {
              customRender: 'operation'
            }
          }
        ],
        visible: false,
        normal: 0,
        alert: 0,
        danger: 0
      }
    },
    created () {
      this.$http.get('/users')
        .then((resp) => {
          if (resp.body.status === 401) {
            this.$message.error('请先登录')
            this.$router.push('/login')
          } else {
            this.data = resp.body.data
            this.statistics()
          }
        }, (error) => {
          if (error.status === 401) {
            this.$message.error('请先登录')
            this.$router.push('/login')
          } else {
            this.$message.error('未知错误')
          }
        })
    },
    methods: {
      handleSearch (selectedKeys, confirm, dataIndex) {
        confirm()
        this.searchText = selectedKeys[0]
        this.searchedColumn = dataIndex
      },

      handleReset (clearFilters) {
        clearFilters()
        this.searchText = ''
      },
      statusChange (openid, status) {
        this.$http.put('/user/status', { openid: openid, status: status }, { emulateJSON: true })
          .then((resp) => {
            if (resp.body.status === 200) {
              const newData = [...this.data]
              const target = newData.filter(item => item.openid === openid)[0]
              if (target) {
                target.status = status
                this.data = newData
              }
              this.$message.success('此人健康状态已改变')
            } else {
              this.$message.error(resp.body.msg)
            }
          }, (error) => {
            console.log(error)
            if (error.status === 401) {
              this.$message.error('请先登录')
              this.$router.push('/login')
            } else {
              this.$message.error('未知错误')
            }
          })
      },
      onChange (pagination, filters, sorter) {
        console.log('params', pagination, filters, sorter)
      },
      statistics () {
        this.normal = 0
        this.alert = 0
        this.danger = 0
        this.data.forEach((item) => {
          if (item.status === 0) {
            this.normal++
          } else if (item.status === 1) {
            this.alert++
          } else {
            this.danger++
          }
        })
      },
      tableToExcel () {
        let str = '<tr><td>姓名</td><td>地址</td><td>电话</td><td>是否小区住户</td><td>健康状态</td></tr>'
        // 循环遍历，每行加入tr标签，每个单元格加td标签
        for (let i = 0; i < this.data.length; i++) {
          str += '<tr>'
          str += `<td>${this.data[i].name + '\t'}</td>`
          str += `<td>${this.data[i].address + '\t'}</td>`
          str += `<td>${this.data[i].phone + '\t'}</td>`
          if (this.data[i].isResident === 0) {
            str += '<td>否</td>'
          } else {
            str += '<td>是</td>'
          }
          if (this.data[i].status === 0) {
            str += '<td>健康</td>'
          } else if (this.data[i].status === 1) {
            str += '<td>预警</td>'
          } else {
            str += '<td>高危</td>'
          }
          str += '</tr>'
        }
        // Worksheet名
        const worksheet = '用户健康状态表'
        const uri = 'data:application/vnd.ms-excel;base64,'

        // 下载的表格模板数据
        const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40" lang="en">
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`
        // 下载模板
        const link = document.createElement('a')
        link.href = uri + this.base64(template)
        // 对下载的文件命名
        link.download = '用户健康状态.xls'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      },
      base64 (s) {
        return window.btoa(unescape(encodeURIComponent(s)))
      }
    }
  }
</script>
<style scoped>
  .highlight {
    background-color: rgb(255, 192, 105);
    padding: 0;
  }
  .container{
  }
  p {
    font-size: 18px;
  }
</style>
